##############################################################
##############################################################
### Replication Materials for
### Stefan Müller and Liam Kneafsey:
### Evidence for the Irrelevance of Irrelevant Events
### Political Science Research and Methods
###
### Please get in touch with the authors if you have any questions: 
### stefan.mueller@ucd.ie
### Note: 0000_readme.pdf contains 
### instructions and details about each script and dataset
##############################################################
##############################################################

## load packages

library(tidyr)       # CRAN v1.1.3
library(dplyr)       # CRAN v1.0.5
library(cowplot)     # CRAN v1.1.1
library(stringr)     # CRAN v1.4.0
library(car)         # CRAN v3.0-10
library(cobalt)      # CRAN v4.2.4
library(WeightIt)    # CRAN v0.11.0
library(survey)      # CRAN v4.0
library(lme4)        # CRAN v1.1-26
library(broom)       # CRAN v0.7.4
library(broom.mixed) # CRAN v0.2.6
library(lubridate)   # CRAN v1.7.10
library(ggplot2)     # CRAN v3.3.3
library(jtools)      # CRAN v2.1.2
library(ebal)        # CRAN v0.1-6

here::here()
## alternatively, set working directory manually
## setwd("...")


## custom ggplot2 scheme

source("function_theme_base.R")

## load INES data and indicators of "unexpected"/suprising events (= GAA matches)

dat_merged_prepost_raw <- readRDS("data_unexpected_events.rds")



## check how often each respondent appears in the dataset

## 142 respondents appear three times, 698 respondents appear twice
## this happens because a county played at two subsequent weekends
## or because a constituency could be merged with two counties
## below, we show that results remain unchanged when we focus only 
## on respondents who are merged with a single match

## number of games
dat_merged_prepost_raw %>% 
    select(winner, date) %>% 
    unique() %>% 
    nrow()

dat_n <- dat_merged_prepost_raw %>% 
    group_by(respondent_id) %>% 
    summarise(n = n()) 

dat_merged_prepost <- dat_merged_prepost_raw %>% 
    group_by(respondent_id) %>% 
    mutate(n_respondent_included = n()) %>% 
    ungroup()



## Figure 4 ----
## loess plots

## check that difference to match is ±6 days
summary(dat_merged_prepost$difference)


ggplot(filter(dat_merged_prepost, !is.na(county_winner)), # is.na county winner excludes draws
       aes(x = difference, 
           y = like_dislike_pm, 
           colour = pre_winner_loser)) +
    geom_jitter(alpha = 0.2) +
    scale_color_grey(start = 0, end = 0.7) +
    scale_x_continuous(breaks = c(seq(-6, 6, 1))) +
    geom_smooth(aes(colour = type), size = 1.5, span = 0.75) + 
    geom_vline(xintercept = 0, linetype = "dashed") +
    facet_grid(year_sport_label~county_winner) +
    scale_color_manual(values = c("black", "black", "red", "darkgreen", "grey50")) + 
    labs(x = "Days before/after match", 
         y = "Dislike/Like of Prime Minister") +
    theme(legend.position = "none")
ggsave("fig_04.pdf", 
       width = 9, height = 6.5)


## check distribution of respondents
dat_merged_prepost_valid <- filter(dat_merged_prepost, 
                                   !is.na(like_dislike_pm))


table(dat_merged_prepost_valid$sport,
      dat_merged_prepost_valid$county_winner)
nrow(dat_merged_prepost_valid)

table(dat_merged_prepost$post_match)

## recode some variables to factors
dat_merged_prepost$sport <- factor(dat_merged_prepost$sport)
dat_merged_prepost$year <- factor(dat_merged_prepost$year)
dat_merged_prepost$type <- factor(dat_merged_prepost$type)
dat_merged_prepost$county_winner <- factor(dat_merged_prepost$county_winner)
dat_merged_prepost$county_gaa <- factor(dat_merged_prepost$county_gaa)
dat_merged_prepost$stronghold_win_loss <- factor(dat_merged_prepost$stronghold_win_loss)
dat_merged_prepost$income_cat <- factor(dat_merged_prepost$income_cat)
dat_merged_prepost$voted_last_election <- factor(dat_merged_prepost$voted_last_election)

table(dat_merged_prepost$county_winner,useNA = "always")

## prepare dataset for t-tests
dat_merged_ttests <- dat_merged_prepost %>% 
    mutate(before_after = ifelse(difference > 0, "Post", 
                                 ifelse(difference < 0, "Pre", NA))) %>% 
    filter(!is.na(before_after))

summary(dat_merged_ttests$difference)

## determine difference (2 to 6 days)
diffs <- c(2:6)

## emtpy data frame to store the results
results_ttest_pm <- data.frame()

for (i in diffs) {
    dat_subset <- dat_merged_ttests %>% 
        filter(difference >= -i & difference <= i) 
    
    result_pm <- dat_subset %>% 
        group_by(year_sport, county_winner) %>% 
        do(tidy(t.test(like_dislike_pm ~ before_after, data = .))) %>%
        filter(!is.na(county_winner)) %>% 
        mutate(difference = i,
               n = nrow(dat_subset))
    
    results_ttest_pm <- bind_rows(result_pm, results_ttest_pm)
}

results_ttest_pm$county_winner <- factor(results_ttest_pm$county_winner, levels = c("Winner", "Loser"))

results_ttest_pm <- results_ttest_pm %>% 
    mutate(difference = paste0("±", difference))

## Figure 5 ----
ggplot(results_ttest_pm, aes(x = factor(difference), y = estimate, 
                             ymin = conf.low, ymax = conf.high,
                             colour = year_sport,
                             shape = year_sport)) +
    geom_hline(yintercept = 0, linetype = "dashed", colour = "red") +
    geom_pointrange(position = position_dodge(width = 0.4)) + 
    facet_wrap(~county_winner) + 
    scale_colour_grey(start = 0, end = 0.5) +
    scale_shape_manual(values = c(1, 17, 16, 2)) +
    scale_y_continuous(limits = c(-2.5, 3.5),
                       breaks = c(seq(-2, 3, 1))) +
    annotate(geom="text", x = 4.8, y = 2.5, 
             label="More positive",
             color="grey70", size = 4) +
    annotate(geom="text", x = 4.8, y = -2, 
             label="More negative",
             color="grey70", size = 4) +
    labs(x = "Window of days before and after match",
         y = "Difference in evaluation\nof Prime Minister") +
    theme(legend.title = element_blank())
ggsave("fig_05.pdf", width = 9, height = 3.5)



## Entropy Balancing ----

## prepare data for entropy balancing

dat_balance <- dat_merged_ttests %>% 
    select(before_after, gender, income_cat,
           like_dislike_pm, year,
           year_sport, stronghold_win_loss,
           respondent_id,
           sport,
           county_winner, 
           voted_last_election, employment) %>% 
    na.omit() %>% 
    mutate(option = paste(year_sport, stronghold_win_loss, sep = "_")) %>% 
    ungroup() %>% 
    mutate(year_sport_win_loss = paste(year_sport, county_winner), sep = "_") %>% 
    mutate(treatment = car::recode(before_after, "'Post'=1;'Pre'=0")) %>% 
    mutate(sport_win_loss = paste(county_winner, sport), sep = "_") %>% 
    group_by(respondent_id) %>% 
    mutate(n_apperances_respondent = n()) %>% 
    ungroup()


## test entropy balancing workflow here
## weight variables using the ebal method
w_out <- weightit(treatment ~ 
                      gender +
                      income_cat + 
                      voted_last_election +
                      employment, 
                  data = dat_balance,
                  method = "ebal", estimand = "ATT")

w_out

## check that variables are balanced
check_bal <- bal.tab(treatment ~ 
                         gender +
                         income_cat + 
                         voted_last_election +
                         employment,
                     method = "weighting",
                     data = dat_balance, estimand = "ATT", 
                     m.threshold = .05)

check_bal



## winner/loser
option <- unique(dat_balance$county_winner)

option

## run loop with two subsets  (winner/loser)
## store results in data frame
dat_ent_pm_base <- data.frame()

for (i in option) {
    
    ## filter the option
    dat_balance_subset <- filter(dat_balance,
                                 county_winner == i)
    
    
    w_out <- weightit(treatment ~ 
                          gender +
                          income_cat + 
                          voted_last_election +
                          employment, 
                      data = dat_balance_subset,
                      method = "ebal", estimand = "ATT")
    
    obs <- nrow(w_out$covs)
    
    dat_weighted <- svydesign(ids = ~1, weights = get.w(w_out),
                              data = dat_balance_subset)
    
    fit_pm  <- svyglm(like_dislike_pm ~ treatment, 
                      design = dat_weighted)
    
    n <- nrow(dat_balance_subset) / 2
    
    
    entr_tidy <- jtools::summ(fit_pm, confint = TRUE) %>% 
        broom::tidy() %>% 
        filter(term != "(Intercept)") %>% 
        mutate(option = i,
               obs = obs)
    
    dat_ent_pm_base <- bind_rows(entr_tidy, dat_ent_pm_base)
}


dat_table_ebal_base <- dat_ent_pm_base %>% 
    select(option, estimate, conf.low, conf.high, std.error,
           p.value, obs) %>% 
    mutate(estimate = paste0(round(estimate, 2),
                             " [", round(conf.low, 2), ", ",
                             round(conf.high, 2), "]")) %>% 
    select(-starts_with("conf")) %>% 
    rename(Model = option, Treatment = estimate, 
           `Standard error` = std.error,
           `p-value` = `p.value`, N = obs) %>% 
    arrange(Model)

## relevel factor
dat_ent_pm_base$winner_loser <- factor(dat_ent_pm_base$option,
                                       levels = c("Loser", "Winner"))

dat_ent_pm_base$model <- "Full sample"

plot_ebal_main <- ggplot(dat_ent_pm_base, aes(x = winner_loser, y = estimate,
                                              colour = winner_loser,
                                              shape = winner_loser)) + 
    geom_hline(yintercept = 0, colour = "grey30", size = 1, 
               linetype = "dashed") +
    geom_linerange(aes(ymin = estimate - 1.96 * std.error,
                       ymax = estimate + 1.96 * std.error),
                   size = 0.5) +
    geom_linerange(aes(ymin = estimate - 1.645 * std.error,
                       ymax = estimate + 1.645 * std.error),
                   size = 1.3) +
    geom_point(size = 4) +
    coord_flip() +
    facet_wrap(~model) +
    scale_shape_manual(values = c(15, 16)) +
    scale_y_continuous(limits = c(-1.5, 1.5),
                       breaks = c(seq(-1.5, 1.5, 0.5))) +
    scale_colour_manual(values = c("darkred", "darkgreen")) +
    theme(legend.position = "none") +
    labs(y = "ATT (average treatment effect on the treated)",
         x = NULL)
plot_ebal_main


## repeat for winner/loser in hurling and Gaelic football
option_sport <- unique(dat_balance$sport_win_loss)

option_sport

dat_ent_pm_year_sport <- data.frame()
for (i in option_sport) {
    
    dat_balance_subset <- filter(dat_balance,
                                 sport_win_loss == i)
    
    w_out <- weightit(treatment ~ 
                          gender +
                          income_cat + 
                          voted_last_election +
                          employment, 
                      data = dat_balance_subset,
                      method = "ebal", estimand = "ATT")
    
    obs <- nrow(w_out$covs)
    
    dat_survey <- svydesign(ids = ~1, weights = get.w(w_out),
                            data = dat_balance_subset)
    
    fit_pm  <- svyglm(like_dislike_pm ~ treatment, 
                      design = dat_survey)
    
    entr_tidy <- jtools::summ(fit_pm, confint = TRUE) %>% broom::tidy() %>% 
        filter(term != "(Intercept)") %>% 
        mutate(option = i,
               obs = obs)
    
    dat_ent_pm_year_sport <- bind_rows(entr_tidy, dat_ent_pm_year_sport)
}


dat_ent_pm_year_sport <- dat_ent_pm_year_sport %>% 
    mutate(option = str_replace_all(option, 'Gaelic football', 'Gaelic_football')) %>% 
    separate(option, into = c("winner_loser", "sport"), sep = " ",
             remove = FALSE) %>% 
    mutate(sport = str_replace_all(sport, "_", " "))

dat_ent_pm_year_sport$winner_loser <- factor(dat_ent_pm_year_sport$winner_loser,
                                             levels = c("Loser", "Winner"))


plot_ebal_sport <- ggplot(dat_ent_pm_year_sport, aes(x = winner_loser, y = estimate,
                                                     colour = winner_loser,
                                                     shape = winner_loser)) + 
    geom_hline(yintercept = 0, colour = "grey30", size = 1, 
               linetype = "dashed") +
    geom_linerange(aes(ymin = estimate - 1.96 * std.error,
                       ymax = estimate + 1.96 * std.error),
                   size = 0.5) +
    geom_linerange(aes(ymin = estimate - 1.645 * std.error,
                       ymax = estimate + 1.645 * std.error),
                   size = 1.3) +
    geom_point(size = 4) +
    coord_flip() +
    scale_shape_manual(values = c(15, 16)) +
    scale_colour_manual(values = c("darkred", "darkgreen")) +
    facet_grid(~sport, scales = "free_y") +
    scale_y_continuous(limits = c(-1.5, 1.5),
                       breaks = c(seq(-1.5, 1.5, 0.5))) +
    theme(legend.position = "none") +
    labs(y = "ATT (average treatment effect on the treated)",
         x = NULL)
plot_ebal_sport


## Figure 6 ----

## combine both plots
cowplot::plot_grid(plot_ebal_main,
                   plot_ebal_sport, nrow = 2)
ggsave("fig_06.pdf",
       width = 9, height = 3.5)



## Robustness Tests and Analyses for Supporting Information ----

## get summary statistics
dat_summary <- dat_merged_prepost %>% 
    select(`Like/dislike Prime Minister` = like_dislike_pm, 
           `Like/dislike affiliated party`= like_dislike_party1, 
           `Difference from matchday`= difference) %>% 
    as.data.frame()

stargazer(dat_summary)


## Table A02 ----
stargazer(dat_summary, type = "html",
          out = "tab_a02.html")



## get matchdays

dat_matches <- dat_merged_prepost %>% 
    select(date, winner) %>% 
    unique() %>% 
    filter(winner != "Draw") %>% 
    mutate(date = as.Date(date)) 

nrow(dat_matches)

## completed surveys

ggplot(data = dat_merged_prepost_valid, 
       aes(x = date_survey_completed)) +
    geom_histogram(binwidth = 1) +
    facet_wrap(~year, scales = "free_x") +
    scale_x_date(breaks = "1 month",
                 date_labels = "%B") +
    geom_vline(xintercept = as.numeric(dat_matches$date), 
               color = "red", 
               linetype = "dotted") +
    labs(y = "Completed questionaires",
         x = "Date")
ggsave("fig_a06.pdf",
       width = 9, height = 3.5)

## check distribution of respondents

dat_merged_prepost_valid <- filter(dat_merged_prepost, 
                                   !is.na(like_dislike_pm))

dat_merged_prepost_valid_grouped <- dat_merged_prepost_valid %>% 
    group_by(difference) %>% 
    summarise(n = n())

## Figure A07 ----
ggplot(dat_merged_prepost_valid_grouped, 
       aes(x = difference, y = n)) + 
    geom_bar(stat = "identity") + 
    labs(x = "Difference to matchday", y = "Count") +
    annotate("text", x = -0.9, y = 400, label = "Matchday", colour = "red",
             size = 4) +
    geom_text(aes(label = n), size = 4, colour = "grey50", nudge_y = 20) +
    geom_vline(xintercept = 0, linetype = "dashed", colour = "red") +
    scale_x_continuous(breaks = c(seq(-6, 6, 1)))
ggsave("fig_a07.pdf", 
       width = 9, height = 3.5)



## check balance of variables before/after matches

table(dat_merged_prepost$post_match, useNA = "always")

## predict whether respondent answered before/after match
balance_glm_full <- glmer(factor(post_match) ~  
                              gender + 
                              income_cat + voted_last_election +
                              employment +  marital_status +
                              (1 | county_gaa), 
                          data = dat_merged_prepost,
                          na.action = na.exclude,
                          family = binomial(link = "logit"))


## repeat analysis and increase number 
## of days before and after match

dat_merged_prepost <- dat_merged_prepost %>% 
    mutate(difference_abs = abs(difference))

balance_glm_1 <- update(balance_glm_full, 
                        data = filter(dat_merged_prepost,
                                      difference_abs <= 1))


balance_glm_2 <- update(balance_glm_full, 
                        data = filter(dat_merged_prepost,
                                      difference_abs <= 2))

balance_glm_3 <- update(balance_glm_full, 
                        data = filter(dat_merged_prepost,
                                      difference_abs <= 3))

balance_glm_4 <- update(balance_glm_full, 
                        data = filter(dat_merged_prepost,
                                      difference_abs <= 4))

balance_glm_5 <- update(balance_glm_full, 
                        data = filter(dat_merged_prepost,
                                      difference_abs <= 5))

balance_glm_6 <- update(balance_glm_full, 
                        data = filter(dat_merged_prepost,
                                      difference_abs <= 6))


prop.table(table(dat_merged_prepost$marital_status)) * 100

(table(dat_merged_prepost$marital_status))

prop.table(table(dat_merged_prepost$employment)) * 100

(table(dat_merged_prepost$employment)) 

## tidy output for plot
bal_2 <- broom.mixed::tidy(balance_glm_2) %>% mutate(difference = "2")
bal_3 <- broom.mixed::tidy(balance_glm_3) %>% mutate(difference = "3")
bal_4 <- broom.mixed::tidy(balance_glm_4) %>% mutate(difference = "4")
bal_5 <- broom.mixed::tidy(balance_glm_5) %>% mutate(difference = "5")
bal_6 <- broom.mixed::tidy(balance_glm_6) %>% mutate(difference = "6")

## bind all estimates
bal_full <- bind_rows(bal_2, bal_3, bal_4, bal_5, bal_6) %>% 
    filter(term != "sd_(Intercept).county_gaa") %>% 
    filter(term != "(Intercept)") %>% 
    mutate(difference = paste0("±", difference, " days"))

table(bal_full$term)

## recode variables
recode_bals <- "'employmentat work part-time(<30hrs)'='Employment: Work part-time';
                 'employmentengaged in home duties'='Employment: Engaged in home duties';
                 'employmentlong term sick or disabled'='Employment: Long term sick or disabled'; 
                 'employmentother'='Employment: Other';
                 'employmentrelative assisting/unpaid family worker'='Employment: Unpaid family worker';
                 'employmentretired'='Employment: Retired';
                 'employmentstudent'='Employment: Student';
                 'employmentunemployed and seeking work'='Employment: Unemployed and seeking work';
                 'genderfemale'='Gender: Female';
                 'income_cat2'='Income: Category 2';
                 'income_cat3'='Income: Category 3';
                 'income_cat4'='Income: Category 4';
                 'income_cat5'='Income: Category 5';
                 'marital_statusdivorced'='Marital status: Divorced';
                 'marital_statusnever married'='Marital status: Never married';
                 'marital_statusseparated'='Marital status: Separated';
                 'marital_statuswidowed'='Marital status: Widowed';
                 'voted_last_electionYes'='Voted last election: Yes'"


bal_full <- bal_full %>% 
    mutate(term_clean = car::recode(term, "'employmentat work part-time(30hrs)'='Employment - Work part-time';
                                  'employmentengaged in home duties'='Employment - Engaged in home duties';
                                  'employmentlong term sick or disabled'='Employment - Long term sick or disabled'; 
                                  'employmentother'='Employment - Other';
                                  'employmentrelative assisting/unpaid family worker'='Employment - Unpaid family worker';
                                  'employmentretired'='Employment - Retired';
                                  'employmentstudent'='Employment - Student';
                                  'employmentunemployed and seeking work'='Employment - Unemployed and seeking work';
                                  'genderfemale'='Gender - Female';
                                  'income_cat2'='Income - Category 2';
                                  'income_cat3'='Income - Category 3';
                                  'income_cat4'='Income - Category 4';
                                  'income_cat5'='Income - Category 5';
                                  'marital_statusdivorced'='Marital status - Divorced';
                                  'marital_statusnever married'='Marital status - Never married';
                                  'marital_statusseparated'='Marital status - Separated';
                                  'marital_statuswidowed'='Marital status - Widowed';
                                  'voted_last_electionYes'='Voted last election - Yes'"))

head(bal_full$term_clean)

## remove sd__(Intercept)
bal_full <- filter(bal_full, term != "sd__(Intercept)")

## Figure A24 ----
ggplot(bal_full, aes(x = reorder(term_clean, desc(term_clean)),
                     y = estimate)) +
    geom_hline(yintercept = 0, colour = "red", 
               linetype = "dashed") +
    geom_linerange(aes(ymin = estimate - 1.96 * std.error,
                       ymax = estimate + 1.96 * std.error),
                   colour = "black", size = 0.3) +
    geom_linerange(aes(ymin = estimate - 1.645 * std.error,
                       ymax = estimate + 1.645 * std.error),
                   size = 0.9) +
    geom_point(size = 2) +
    facet_wrap(~difference) +
    coord_flip() + 
    labs(y = "Coefficient", x = NULL)
ggsave("fig_a24.pdf", 
       width = 9, height = 7.5)




## Robustness: Entropy Balancing

## repeat, but only keep respondents who appear once

#option_sport <- unique(dat_balance$sport_win_loss)

option


dat_ent_pm_onlyonetreatment <- data.frame()

for (i in option) {
    
    dat_balance_subset <- dat_balance %>% 
        filter(county_winner == i) %>% 
        filter(n_apperances_respondent == 1) ## only keep respondents who are matched to a single game
    
    
    w_out <- weightit(treatment ~ 
                          gender +
                          income_cat + 
                          voted_last_election +
                          employment, 
                      data = dat_balance_subset,
                      method = "ebal", 
                      estimand = "ATT")
    
    obs <- nrow(w_out$covs)
    
    d.w <- svydesign(ids = ~1, weights = get.w(w_out),
                     data = dat_balance_subset)
    
    fit_pm  <- svyglm(like_dislike_pm ~ treatment, 
                      design = d.w)
    
    entr_tidy <- jtools::summ(fit_pm, confint = TRUE) %>% broom::tidy() %>% 
        filter(term != "(Intercept)") %>% 
        mutate(option = i,
               obs = obs)
    
    dat_ent_pm_onlyonetreatment <- bind_rows(entr_tidy, dat_ent_pm_onlyonetreatment)
}



dat_ent_pm_onlyonetreatment$model <- "All respondents"
dat_ent_pm_base$model <- "Respondents who experienced only one match"

dat_ent_pm_robustness <- bind_rows(dat_ent_pm_onlyonetreatment,
                                   dat_ent_pm_base) 


dat_ent_pm_robustness$winner_loser <- factor(dat_ent_pm_robustness$option,
                                             levels = c("Loser", "Winner"))




## Figure A25 ----

ggplot(dat_ent_pm_robustness, 
       aes(x = winner_loser, y = estimate,
           colour = winner_loser)) + 
    geom_hline(yintercept = 0, colour = "grey30", size = 1, 
               linetype = "dashed") +
    geom_linerange(aes(ymin = estimate - 1.96 * std.error,
                       ymax = estimate + 1.96 * std.error),
                   size = 0.5,
                   position = position_dodge(width = 0.5)) +
    geom_linerange(aes(ymin = estimate - 1.645 * std.error,
                       ymax = estimate + 1.645 * std.error),
                   size = 1.3,
                   position = position_dodge(width = 0.5)) +
    geom_point(size = 4,
               position = position_dodge(width = 0.5)) +
    coord_flip() +
    scale_shape_manual(values = c(15, 16),
                       guide = guide_legend(reverse = TRUE)) +
    scale_colour_manual(values = c("darkred", "darkgreen"), name = NULL) +
    facet_wrap(~model, nrow = 2) +
    guides(colour=FALSE)  +
    labs(y = "ATT (average treatment effect on the treated)",
         x = NULL) +
    theme(legend.title = element_blank(), 
          legend.position = "none")
ggsave("fig_a25.pdf", 
       width = 10, height = 4)



## rerun t-tests but use evalution of preferred party
dat_merged_ttests <- dat_merged_prepost %>% 
    mutate(before_after = ifelse(difference > 0, "Post", 
                                 ifelse(difference < 0, "Pre", NA))) %>% 
    filter(!is.na(before_after))


## run t-tests for different ranges of days (from 2 to 6 days)
diffs <- c(2:6)

results_ttest_party <- data.frame()

for (i in diffs) {
    dat_subset <- dat_merged_ttests %>% 
        filter(difference >= -i & difference <= i) 
    
    ## run t-test (grouped by year and winner)
    ## whether before/after comparison changed approval with party
    result_party <- dat_subset %>% 
        group_by(year_sport, county_winner) %>% 
        do(tidy(t.test(like_dislike_party1 ~ before_after, data = .,
                       na.action = na.exclude))) %>%
        filter(!is.na(county_winner)) %>% 
        mutate(difference = i)
    
    results_ttest_party <- bind_rows(result_party, results_ttest_party)
}


## create variable with difference
results_ttest_party <- results_ttest_party %>% 
    mutate(difference = paste0("±", difference))

## relevel factor
results_ttest_party$county_winner <- factor(results_ttest_party$county_winner, 
                                            levels = c("Winner", "Loser"))


## Figure A27 ----
ggplot(results_ttest_party, aes(x = factor(difference), y = estimate, 
                                ymin = conf.low, ymax = conf.high,
                                colour = year_sport,
                                shape = year_sport)) +
    geom_hline(yintercept = 0, linetype = "dashed", colour = "red") +
    geom_pointrange(position = position_dodge(width = 0.4)) + 
    facet_wrap(~county_winner) + 
    scale_colour_grey(start = 0, end = 0.5) +
    scale_shape_manual(values = c(1, 17, 16, 2)) +
    scale_y_continuous(limits = c(-3.5, 3.5), 
                       breaks = c(seq(-3, 3, 1))) +
    annotate(geom="text", x = 4.8, y = 2.5, 
             label="More positive",
             color="grey70", size = 4) +
    annotate(geom="text", x = 4.8, y = -2.5, 
             label="More negative",
             color="grey70", size = 4) +
    labs(x = "Window of days before and after match",
         y = "Difference in evaluation\nof favourite party") +
    theme(legend.title = element_blank())
ggsave("fig_a27.pdf", 
       width = 9, height = 3.5)



## repeat LOESS analysis with evaluation of preferred party
ggplot(filter(dat_merged_prepost, !is.na(county_winner)), # remove draws
       aes(x = difference, 
           y = like_dislike_party1, 
           colour = pre_winner_loser)) +
    geom_jitter(alpha = 0.2) +
    geom_smooth(aes(colour = type), size = 1.5, span = 0.75) + 
    scale_color_manual(values = c("black", "black", "red", "darkgreen", "grey50")) +
    geom_vline(xintercept = 0, linetype = "dashed") +
    facet_grid(year_sport_label~county_winner) +
    scale_x_continuous(breaks = c(seq(-6, 6, 1))) +
    labs(x = "Days before/after match", 
         y = "Dislike/Like of first-preference party") +
    theme(legend.position = "none")
ggsave("fig_a26.pdf", 
       width = 9, height = 6.5)


## only select members of the GAA

## Figure A28 ----
ggplot(filter(dat_merged_prepost, 
              gaa_member == "yes" & !is.na(county_winner)),
       aes(x = difference, 
           y = like_dislike_pm,
           colour = pre_winner_loser)) +
    geom_jitter(alpha = 0.2) +
    scale_color_grey(start = 0, end = 0.7) +
    scale_x_continuous(breaks = c(seq(-6, 6, 1))) +
    geom_smooth(aes(colour = type), size = 1.5, span = 0.75) + 
    geom_vline(xintercept = 0, linetype = "dashed") +
    facet_grid(year_sport_label~county_winner) +
    scale_color_manual(values = c("black", "black", "red", "darkgreen", "grey50")) +
    labs(x = "Days before/after match", 
         y = "Dislike/Like of Prime Minister") +
    theme(legend.position = "none")
ggsave("fig_a28.pdf", 
       width = 9, height = 4)



## only filter matches in later stages of competition
dat_merged_july_august <- dat_merged_prepost %>% 
    filter(month %in% c(7, 8))


## Figure A29 ----
ggplot(filter(dat_merged_july_august, !is.na(county_winner)),
       aes(x = difference, 
           y = like_dislike_pm,
           colour = pre_winner_loser)) +
    geom_jitter(alpha = 0.2) +
    scale_color_manual(values = c("black", "black", "red", "darkgreen", "grey50")) +  
    geom_smooth(aes(colour = type), size = 1.5, span = 0.75) + 
    geom_vline(xintercept = 0, linetype = "dashed") +
    facet_grid(year_sport_label~county_winner) +
    scale_x_continuous(breaks = c(seq(-6, 6, 1))) +
    labs(x = "Days before/after match", 
         y = "Dislike/Like of Prime Minister") +
    theme(legend.position = "none")
ggsave("fig_a29.pdf", 
       width = 9, height = 6.5)


## script executed successfully on
date()

sessionInfo()
